/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  MoreOwnerInfoActivity.java   
 * @Package com.jiyi.activity.owner   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-9-7 下午2:56:40   
 * @version V1.0     
 */
package com.jiyi.activity.new_maintenance;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.jiyi.activity.Map_MyLocationActivity;
import com.jiyi.activity.SinglePicActivity;
import com.jiyi.adapter.CommonAdapter;
import com.jiyi.adapter.ViewHolder;
import com.jiyi.bean.owner.OwnerInfoJsonBean;
import com.jiyi.bean.owner.OwnerInfoJsonBean.Data.BranchInfo;
import com.jiyi.bean.owner.OwnerInfoJsonBean.Industry;
import com.jiyi.bean.owner.OwnerInfoJsonBean.Supervision;
import com.jiyi.bean.zone.ZoneHaoYouBean;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.event.OwnerLogoChangeEvent;
import com.jiyi.event.UserInfoEvent;
import com.jiyi.inteface.WebApi;
import com.jiyi.view.DateChooseDialog;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.CheckUtil;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.swift.utils.DeviceUtil;
import com.swift.utils.GlideUtil;
import com.swift.utils.PhotoUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * @ClassName: MoreOwnerInfoActivity
 * @Description:TODO(完善业主资料)
 * @author: HYM
 * @date: 2017-9-7 下午2:56:40
 * 
 */
public class MoreOwnerInfoActivity extends SinglePicActivity {

	/* 头部 */
	@BindView(R.id.tvBack)
	TextView tvBack;
	@BindView(R.id.tvTitle)
	TextView tvTitle;
	@BindView(R.id.tvSearch)
	TextView tvSearch;

	@BindView(R.id.ivLogo)
	ImageView ivLogo;
	@BindView(R.id.ivLocation)
	ImageView ivLocation;
	@BindView(R.id.etFee)
	EditText etFee;
	@BindView(R.id.tvStartDate)
	TextView tvStartDate;
	@BindView(R.id.tvEndDate)
	TextView tvEndDate;
	@BindView(R.id.etAddress)
	EditText etAddress;
	@BindView(R.id.etOwnerName)
	EditText etOwnerName;
	@BindView(R.id.etTel)
	EditText etTel;
	@BindView(R.id.etUserName)
	EditText etUserName;
	@BindView(R.id.etMobile)
	EditText etMobile;
	@BindView(R.id.state_supervision)
	Spinner state_supervision;
	@BindView(R.id.state_industry)
	Spinner state_industry;


	private final int CROP_SMALL_PICTURE = 4;
	private String companyId;
	// 进度条
	Dialog dialog;

	// 定位事件
	final int LOCATION = 5;
	// 监管列表适配器
	CommonAdapter<Supervision> stateSupervisionAdapter;
	// 监管列表数据源
	List<Supervision> supervisionDataList = new ArrayList<Supervision>();
	// 行业列表适配器
	CommonAdapter<Industry> stateIndustryAdapter;
	// 行业列表数据源
	List<Industry> industryDataList = new ArrayList<Industry>();
	// 经纬度
	String latitude, longitude;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_more_owner_info);
		ButterKnife.bind(this);
		init();
	}

	@Override
	protected void onDestroy() {
		hideDialog(dialog);
		super.onDestroy();
	}

	private void init() {
		getIntentData();
		setTop();
		setViewStatus();
		setAdapter();
		getData();
	}

	private void getIntentData() {
		companyId = getIntent().getStringExtra("companyId");
	}

	private void getData() {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("company_id", companyId);

		VolleyRequest.StringRequestPost(this,
				WebApi.MAINTENANCE_OWNER_MORE_INFO, "", params,
				new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {

								Log.e("dsf sdfds  ", result);
								OwnerInfoJsonBean temp = new Gson().fromJson(
										result, OwnerInfoJsonBean.class);
								setIndustryInfo(temp.getData().getIndustry());
								setSupervisionInfo(temp.getData()
										.getSuperviseList());
								setOwnerInfo(temp.getData().getBranchInfo());
							} else if (status.equals("404")
									&& info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg(
										"尚未登录或该用户在其他地方登录，请重新登录！");
								// 清除环信登录
								UserHelp.getInstance().clearUser(
										AppBase.Context, true);
								return;
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
						}
					}

					@Override
					public void stringError(VolleyError error) {
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}

	private void setTop() {
		tvTitle.setText("完善资料");
		tvSearch.setCompoundDrawables(null, null, null, null);
		tvSearch.setText("取消");
	}

	private void setViewStatus() {
		// 设置必填项检测提示
		etOwnerName.setTag(R.id.tag_view_empty, "公司名称不能为空");
		etAddress.setTag(R.id.tag_view_empty, "地址不能为空");
		etTel.setTag(R.id.tag_view_empty, "企业电话不能为空");
		etUserName.setTag(R.id.tag_view_empty, "负责人不能为空");
		etMobile.setTag(R.id.tag_view_empty, "负责人电话不能为空");
		tvStartDate.setTag(R.id.tag_view_empty, "开始时间不能为空");
		tvEndDate.setTag(R.id.tag_view_empty, "结束时间不能为空");
		etFee.setTag(R.id.tag_view_empty, "费用时间不能为空");
	}

	private void setAdapter() {

		stateSupervisionAdapter = new CommonAdapter<Supervision>(this,
				supervisionDataList, R.layout.item_state_small) {

			@Override
			public void convert(ViewHolder holder, Supervision t) {
				holder.setText(R.id.state_name, t.getName());
			}
		};
		state_supervision.setAdapter(stateSupervisionAdapter);

		stateIndustryAdapter = new CommonAdapter<Industry>(this,
				industryDataList, R.layout.item_state_small) {

			@Override
			public void convert(ViewHolder holder, Industry t) {
				holder.setText(R.id.state_name, t.getIndustry());
			}
		};
		state_industry.setAdapter(stateIndustryAdapter);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == RESULT_OK) { // 如果返回码是可以用的
			switch (requestCode) {
			case CAMARE_CODE:
				startPhotoZoom(mCameraUri); // 开始对图片进行裁剪处理
				break;
			case CHOOSE_PICTURE:
				startPhotoZoom(data.getData()); // 开始对图片进行裁剪处理
				break;
			case CROP_SMALL_PICTURE:
				if (data != null) {
					setImageToView(data); // 让刚才选择裁剪得到的图片显示在界面上
				}
				break;
			case LOCATION:
				etAddress.setText(data.getStringExtra("address"));
				latitude = data.getStringExtra("latitude");
				longitude = data.getStringExtra("longitude");
				break;
			}

		}

	}

	/**
	 * 裁剪图片方法实现
	 * 
	 * @param uri
	 */
	protected void startPhotoZoom(Uri uri) {
		if (uri == null) {
			Log.i("tag", "The uri is not exist.");
		}
		mCameraUri = uri;
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 设置裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 150);
		intent.putExtra("outputY", 150);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, CROP_SMALL_PICTURE);
	}

	protected void setImageToView(Intent data) {
		Bundle extras = data.getExtras();
		if (extras != null) {
			Bitmap photo = extras.getParcelable("data");
			// photo = PhotoUtils.toRoundBitmap(photo, CameraUri); //
			// 这个时候的图片已经被处理成圆形的了
			ivLogo.setImageBitmap(photo);
			filePath = PhotoUtils.savePhoto(photo, PhotoUtils.USER_LOGO,
					String.valueOf(System.currentTimeMillis()));
			// uploadPic(photo);
		}
	}

	private void uploadPic(Bitmap bitmap) {
		String imagePath = PhotoUtils.savePhoto(bitmap, PhotoUtils.USER_LOGO,
				String.valueOf(System.currentTimeMillis()));
		Log.e("imagePath", imagePath + "");
		if (imagePath != null) {
			// 拿着imagePath上传了
			String webApi = WebApi.ZONE_LOGO_UPLOAD;
			Map<String, String> params = new HashMap<String, String>();
			params.put(AppConfig.ACCESS_TOKEN,
					UserInfoUtil.getCurrentUserAccessToken());

			PostFormBuilder postForm = OkHttpUtils.post().url(webApi);
			postForm.params(params);
			if (!TextUtils.isEmpty(imagePath)) {
				File file = new File(imagePath);
				postForm.addFile("head_path", "user_logo.jpg", file);
			}

			dialog = showDialog(dialog);
			postForm.build().execute(new StringCallback() {

				@Override
				public void onError(Call arg0, Exception exception, int arg2) {
					// 删除临时头像
					PhotoUtils.RecursionDeleteFile(new File(
							PhotoUtils.USER_LOGO));
					hideDialog(dialog);
					ToastUtil.getInstances().showMsg(exception.getMessage());
				}

				@Override
				public void onResponse(String result, int arg1) {
					try {
						JSONObject obj = new JSONObject(result);
						String status = obj.getString("status");
						String info = obj.getString("info");
						if (status.equals("200")) {
							ToastUtil.getInstances().showMsg(info);
							String data = obj.getString("data");
							JSONObject dataJson = new JSONObject(data);
							String url = dataJson.getString("url");
							if (!TextUtils.isEmpty(url)) {
								ZoneHaoYouBean zoneHaoYouBean = new ZoneHaoYouBean();
								zoneHaoYouBean.setHead_path(url);
								EventBus.getDefault().postSticky(
										new UserInfoEvent(zoneHaoYouBean));
								UserInfoUtil.setCurrentUserLogo(url);
							}
						} else if (status.equals("404")
								&& info.contains("尚未登录")) {
							ToastUtil.getInstances().showMsg(
									"尚未登录或该用户在其他地方登录，请重新登录！");
							// 清除环信登录
							UserHelp.getInstance().clearUser(
									AppBase.Context, true);
							return;
						} else {
							ToastUtil.getInstances().showMsg(info);
						}
					} catch (JSONException e) {
						e.printStackTrace();
					} finally {
						// 删除临时头像
						PhotoUtils.RecursionDeleteFile(new File(
								PhotoUtils.USER_LOGO));
						hideDialog(dialog);
					}
				}
			});
		}

	}

	@OnClick({ R.id.tvBack, R.id.tvSearch, R.id.ivLogo, R.id.tvStartDate,
			R.id.tvEndDate, R.id.tvPost, R.id.ivLocation })
	public void onClick(View view) {
		DateChooseDialog.Builder builder;
		Intent intent = null;
		switch (view.getId()) {
		case R.id.tvBack:
		case R.id.tvSearch:
			finish();
			break;
		case R.id.tvPost:
			// 保存
			if (CheckUtil.checkView(etOwnerName, etAddress, etTel, etUserName,
					etMobile, etFee, tvStartDate, tvEndDate)) {
				doPost();
			}
			break;
		case R.id.ivLogo:
			mPickPopView.showPopWindow();
			break;
		case R.id.tvStartDate:
			// 开始时间选择
			builder = new DateChooseDialog.Builder(this);
			builder.setTitle("选择日期");
			builder.setTextView((TextView) findViewById(R.id.tvStartDate));
			builder.setPositiveButton("确定",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							// 设置你的操作事项
						}
					});

			builder.setNegativeButton("取消",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
			builder.create().show();
			break;
		case R.id.tvEndDate:
			builder = new DateChooseDialog.Builder(this);
			builder.setTitle("选择日期");
			builder.setTextView((TextView) findViewById(R.id.tvEndDate));
			builder.setPositiveButton("确定",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							// 设置你的操作事项
						}
					});

			builder.setNegativeButton("取消",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
			builder.create().show();
			break;
		case R.id.ivLocation:
			// 定位
			if (!DeviceUtil.getInstance().isGpsEnable()) {
				ToastUtil.getInstances().showMsg("请打开GPS定位");
				return;
			}

			intent = new Intent(this, Map_MyLocationActivity.class);
			intent.putExtra("mapType", 1);
			intent.putExtra("latitude", latitude);
			intent.putExtra("longitude", longitude);
			intent.putExtra("address", etAddress.getText().toString());
			startActivityForResult(intent, LOCATION);
			break;
		default:
			break;
		}
	}

	/**
	 * @author: HYM
	 * @Title: setSupervisionInfo
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param getSupervision
	 *            void
	 * @date: 2017-5-19
	 */
	protected void setSupervisionInfo(List<Supervision> getSupervision) {
		if (getSupervision.size() > 0) {
			supervisionDataList.clear();
			supervisionDataList.addAll(getSupervision);
			stateSupervisionAdapter.notifyDataSetChanged();
		}
	}

	/**
	 * @author: HYM
	 * @Title: setIndustryInfo
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param industry
	 *            void
	 * @date: 2017-5-19
	 */
	protected void setIndustryInfo(List<Industry> industry) {
		if (industry.size() > 0) {
			industryDataList.clear();
			industryDataList.addAll(industry);
			stateIndustryAdapter.notifyDataSetChanged();
		}
	}

	/**
	 * @author: HYM
	 * @Title: setOwnerInfo
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param branchInfo
	 *            void
	 * @date: 2017-5-19
	 */
	protected void setOwnerInfo(BranchInfo branchInfo) {
		etOwnerName.setText(branchInfo.getName());
		etAddress.setText(branchInfo.getAddress());
		tvStartDate.setText(branchInfo.getExpire_start_time().equals(
				"0000-00-00") ? "" : branchInfo.getExpire_start_time());
		tvEndDate.setText(branchInfo.getExpire_time().equals("0000-00-00") ? ""
				: branchInfo.getExpire_time());
		etFee.setText(branchInfo.getYear_premium());
		etMobile.setText(branchInfo.getPrincipal_tel());
		etUserName.setText(branchInfo.getPrincipal());
		etTel.setText(branchInfo.getPhone());

		state_supervision.setSelection(getSupervisionById(branchInfo
				.getSupervised_id()));
		state_industry
				.setSelection(getIndustryById(branchInfo.getIndustry_id()));
		latitude = branchInfo.getGeo_lat();
		longitude = branchInfo.getGeo_lng();
		GlideUtil.load(context, branchInfo.getCompany_logo(), ivLogo);
		// Glide.with(this).load(branchInfo.getCompany_logo()).transform(new
		// GlideRoundTransform(this)).into(ivLogo);
		// Glide.with(context).load(branchInfo.getCompany_logo()).asBitmap().centerCrop().placeholder(R.drawable.maintenace).into(new
		// BitmapImageViewTarget(ivLogo) {
		// @Override
		// protected void setResource(Bitmap resource) {
		// RoundedBitmapDrawable roundBitmapDrawable =
		// RoundedBitmapDrawableFactory.create(context.getResources(),
		// resource);
		// roundBitmapDrawable.setCornerRadius(100);
		// ivLogo.setImageDrawable(roundBitmapDrawable);
		// }
		// });
	}

	int getSupervisionById(String id) {
		for (int i = 0; i < supervisionDataList.size(); i++) {
			Supervision supervision = supervisionDataList.get(i);
			if (supervision.getId().equals(id)) {
				return i;
			}
		}
		return 0;
	}

	int getIndustryById(String id) {
		for (int i = 0; i < industryDataList.size(); i++) {
			Industry industry = industryDataList.get(i);
			if (industry.getId().equals(id)) {
				return i;
			}
		}
		return 0;
	}

	void doPost() {
		String webApi = WebApi.MAINTENANCE_OWNER_MORE_INFO_UPLOAD;

		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("id", companyId);
		params.put("name", etOwnerName.getText().toString());
		params.put("address", etAddress.getText().toString());
		params.put("principal", etUserName.getText().toString());
		params.put("principal_tel", etMobile.getText().toString());
		params.put("year_premium", etFee.getText().toString());
		params.put("expire_start_time", tvStartDate.getText().toString());
		params.put("expire_time", tvEndDate.getText().toString());
		params.put("phone", etTel.getText().toString());
		params.put(
				"supervised_id",
				new Gson().fromJson(
						state_supervision.getSelectedItem().toString(),
						Supervision.class).getId());
		params.put(
				"industry_id",
				new Gson().fromJson(
						state_industry.getSelectedItem().toString(),
						Industry.class).getId());
		 params.put("geo_lng", longitude);
		 params.put("geo_lat", latitude);

		PostFormBuilder postForm = OkHttpUtils.post().url(webApi);
		postForm.params(params);
		if (!TextUtils.isEmpty(filePath)) {
			File file = new File(filePath);
			postForm.addFile("branch_logo", "pic.jpg", file);
		}

		dialog = showDialog(dialog);
		postForm.build().execute(new StringCallback() {

			@Override
			public void onError(Call arg0, Exception exception, int arg2) {
				hideDialog(dialog);
				ToastUtil.getInstances().showMsg(exception.getMessage());
			}

			@Override
			public void onResponse(String result, int arg1) {
				try {
					JSONObject obj = new JSONObject(result);
					String status = obj.getString("status");
					String info = obj.getString("info");
					if (status.equals("200")) {
						ToastUtil.getInstances().showMsg(info);
						EventBus.getDefault().post(
								new OwnerLogoChangeEvent(filePath));
						// 删除临时头像
						PhotoUtils.RecursionDeleteFile(new File(
								PhotoUtils.USER_LOGO));
						// finish();
					} else if (status.equals("404") && info.contains("尚未登录")) {
						ToastUtil.getInstances().showMsg(
								"尚未登录或该用户在其他地方登录，请重新登录！");
						// 清除环信登录
						UserHelp.getInstance().clearUser(AppBase.Context,
								true);
						return;
					} else {
						ToastUtil.getInstances().showMsg(info);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				} finally {
					hideDialog(dialog);
				}
			}
		});
	}

}
